package com.decent.common.util.jackson;

import cn.hutool.core.util.EnumUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 枚举返序列化，防止传入空字符串导致序列化失败
 * 如果枚举为空字符串，则返回null
 *
 * @author: wangyan
 * @date: 2021/12/16
 */
@SuppressWarnings("ALL")
public class EnumDeserializer extends JsonDeserializer<Enum> {

    @Override
    public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        if (p.getTextLength() == 0) {
            return null;
        }
        if (Objects.isNull(p.getCurrentValue())) {
            return null;
        }
        Class enumCls = BeanUtils.findPropertyType(p.currentName(), p.getCurrentValue().getClass());
        return EnumUtil.fromString(enumCls, p.getText());
    }
}